package com.bj58.analysis.tools;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import com.bj58.analysis.tools.common.GetObjectToClassUtils;
import com.bj58.analysis.tools.common.bean.LogBean;
import com.bj58.analysis.tools.original.bean.OriginalTrackBean;

public class OriginalGanjiAppTrackAnalysis extends CommonAnalysis {

	@Override
	protected LogBean analysis(String logLine) {
		OriginalTrackBean bean = null;
		if (StringUtils.isNotBlank(logLine)) {
			Map<String, String> map = new HashMap<String, String>();
			//servtime,时间戳
			String servtimePattern="servtime=(.*?)(@|&|$)";
			String servtime=getPartOfLog(servtimePattern, logLine);
			if(StringUtils.isNotBlank(servtime)){
				SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					Date date=format.parse(servtime);
					String tmpEpoch=date.getTime()+"";
					if(StringUtils.isNotBlank(tmpEpoch)&&tmpEpoch.length()>=13){
						String epoch=tmpEpoch.substring(0, 10)+"."+
										tmpEpoch.substring(10, 13);
						map.put("epoch", epoch);
					}
				} catch (ParseException e) {
					
				}
			}
			
			//userip
			String remipPattern="remip=(.*?)(@|&|$)";
			String remip=getPartOfLog(remipPattern, logLine);
			if(StringUtils.isNotBlank(remip))
				map.put("userIp", remip);
			
			//cookieId
			String cookieIdPattern="appinstallationid=(.*?)(@|&|$)";
			String cookieId=getPartOfLog(cookieIdPattern, logLine);
			if(StringUtils.isNotBlank(cookieId))
				map.put("cookieID", cookieId);
			
			//cate
			String catePattern="gc=/(.*?)(@|&|$)";
			String catePath=getPartOfLog(catePattern, logLine);
			if(StringUtils.isNotBlank(catePath)){
				String tmp="";
				String[] catePaths=catePath.split("/",-1);
				//pagetype
				String pageType=catePaths[catePaths.length-2];
				if(StringUtils.isBlank(pageType)||pageType.equals("-"))
					pageType="other";
				
				map.put("pageType", pageType);
				
				for(int i=1;i<catePaths.length-2;i++){
					String tmpCate=catePaths[i];
					if(tmpCate.equals("-"))
						tmpCate="other";
					tmp+=tmpCate+",";
				}
				if(StringUtils.isNotBlank(tmp)){
					tmp=tmp.substring(0, tmp.length()-1);
					map.put("catePath", tmp);
				}
			}
			
			//trackurl
			Map<String, String> trackUrlMap=new HashMap<String, String>();
			//用户浏览器id
			String seqidPattern="seqid=(.*?)(@|&|$)";
			String seqid=getPartOfLog(seqidPattern, logLine);
			if(StringUtils.isNotBlank(seqid))
				trackUrlMap.put("seqid", seqid);
			//每条日志唯一标识
			String reqidPattern="reqid=(.*?)(@|&|$)";
			String reqid=getPartOfLog(reqidPattern, logLine);
			if(StringUtils.isNotBlank(reqid))
				trackUrlMap.put("reqid", reqid);
			
			//登陆后的userid,为登陆为-1
			String ucuPattern="ucuserid=(.*?)(@|&|$)";
			String ucuserid=getPartOfLog(ucuPattern, logLine);
			if(StringUtils.isNotBlank(ucuserid)&&!(ucuserid.equals("-1")))
				map.put("loginUid", ucuserid);
			
			//版本号
			String versionidPattern="versionid=(.*?)(@|&|$)";
			String versionid=getPartOfLog(versionidPattern, logLine);
			if(StringUtils.isNotBlank(versionid))
				trackUrlMap.put("versionid", versionid);
			
			//手机端的imei
			String imeiPattern="imei=(.*?)(@|&|$)";
			String imei=getPartOfLog(imeiPattern, logLine);
			if(StringUtils.isNotBlank(imei))
				trackUrlMap.put("imei", imei);
			
			//customerid
			String customeridPattern="customerid=(.*?)(@|&|$)";
			String customerid=getPartOfLog(customeridPattern, logLine);
			if(StringUtils.isNotBlank(customerid))
				trackUrlMap.put("customerid", customerid);
			
			//agency
			String agencyPattern="agency=(.*?)(@|&|$)";
			String agency=getPartOfLog(agencyPattern, logLine);
			if(StringUtils.isNotBlank(agency))
				trackUrlMap.put("agency", agency);
			
			//unique
			String uniquePatthern="unique_id=(.*?)(@|&|$)";
			String unique_id=getPartOfLog(uniquePatthern, logLine);
			if(StringUtils.isNotBlank(unique_id))
				trackUrlMap.put("unique_id", unique_id);
			
			//areapath
			String areaPattern="cityscriptindex=(.*?)(@|&|$)";
			String area=getPartOfLog(areaPattern, logLine);
			if(StringUtils.isNotBlank(area))
				map.put("areaPath", unique_id);
			
			//其它附加字段
			int beginIndex=logLine.indexOf("@");
			int overIndex=logLine.lastIndexOf("@");
			if(beginIndex!=-1&&beginIndex!=overIndex){
				String tmpLine=logLine.substring(overIndex+1);
				int tmpIndex=tmpLine.indexOf("&");
				String extendField=logLine.substring(beginIndex+1, (overIndex+tmpIndex+1));
				addFieldToTrackUrl(extendField, trackUrlMap);
			}
			if(trackUrlMap!=null&&trackUrlMap.size()!=0){
				String trackUrl=JSONObject.fromObject(trackUrlMap).toString();
				map.put("trackUrl", trackUrl);
			}
			
			if (map != null && map.size() != 0) {
				Object obj = GetObjectToClassUtils.getObjectByMap(
						OriginalTrackBean.class, map);
				if (obj != null)
					bean = (OriginalTrackBean) obj;
			}
		}
		return bean;
	}
	
	//将相关扩展字段添加进入trackurl中
	private void addFieldToTrackUrl(String tmpLine,Map<String, String> trackurlMap){
		if(StringUtils.isNotBlank(tmpLine)&&trackurlMap!=null){
			String[] tmpLines=tmpLine.split("@", -1);
			for(String tmp:tmpLines){
				int tmpIndex=tmp.indexOf("=");
				String tmpKey=tmp.substring(0, tmpIndex);
				String tmpValue=tmp.substring(tmpIndex+1);
				if(StringUtils.isNotBlank(tmpKey)&&StringUtils.isNotBlank(tmpValue))
					trackurlMap.put(tmpKey, tmpValue);
			}
		}
	}
	
	//用正则表达式获取日志中的内容
	private String getPartOfLog(String pattern,String logLine){
		String tmpResult=null;
		Pattern pt=getPattern(pattern);
		Matcher m_e = pt.matcher(logLine);
		while (m_e.find()) {
			String value = m_e.group();
			if(StringUtils.isNotBlank(value)){
				String[] values=value.split("=", 2);
				if(values!=null&&values.length==2){
					String tmpValue=values[1];
					String lastChar=tmpValue.substring(tmpValue.length()-1,tmpValue.length());
					if(lastChar.contains("&")||lastChar.contains("@")){
						tmpResult=tmpValue.substring(0, tmpValue.length()-1);
					}else{
						tmpResult=tmpValue;
					}
					break;
				}
			}
		}
		return tmpResult;
	}
	
	// 获取正则表达式对象
	private Pattern getPattern(String pattern) {
		return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
	}

	@Test
	public void test(){
		String line="gc=/-/-/-/-/39/@data_version=-@city_id=235&reqid=14670432022696f700469-afdb-447f-8ba4-7c8acfd8bbd6&servtime=2016-06-28 00:00:08&remip=112.17.246.118&appinstallationid=249211967&unique_id=64b0f3259471224bbacfcb44591cef6d&customerid=801&dealtime=9";
		OriginalTrackBean bean=(OriginalTrackBean)analysis(line);
		String tmp=bean.toString();
		System.out.println(tmp);
	}
}
